package com.wsyu.springbootbackend.core.auth.config;

import com.wsyu.springbootbackend.core.auth.filter.CustomJwtFilter;
import com.wsyu.springbootbackend.core.auth.filter.CustomUsernamePasswordAuthenticationFilter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


public abstract class AbstractCustomSecurityConfig extends WebSecurityConfigurerAdapter {

    public abstract AuthenticationSuccessHandler authenticationSuccessHandler();

    public abstract AuthenticationFailureHandler authenticationFailureHandler();

    public abstract AuthenticationEntryPoint authenticationEntryPoint();

    public abstract AccessDeniedHandler accessDeniedHandler();

    public abstract CustomJwtFilter jwtFilter();

    public abstract CustomUsernamePasswordAuthenticationFilter usernamePasswordAuthenticationFilter();

    public abstract PasswordEncoder passwordEncoder();


    // region configure(HttpSecurity http)
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers("/login").permitAll()        // 没有任何权限要求，甚至，也没有“登录”要求
                .anyRequest().authenticated(); // 2

        http.exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint())
                .accessDeniedHandler(accessDeniedHandler());

        http.formLogin()
                .successHandler(authenticationSuccessHandler())
                .failureHandler(authenticationFailureHandler());

        http.addFilterAfter(jwtFilter(), UsernamePasswordAuthenticationFilter.class);
        http.addFilterAt(usernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

        http.httpBasic().disable() // 和表单登录功能“互斥”，没用上；
                .formLogin().disable()
                .csrf().disable();      // 安全性设置，一般会关掉它；

        http.sessionManagement()    // 前后端分离项目声明
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
    // endregion


}
